package com.moon.back.service.impl.detemination;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLSentence;
import com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLWord;
import com.hankcs.hanlp.dependency.nnparser.NeuralNetworkDependencyParser;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.tokenizer.StandardTokenizer;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileOperationDecisionSystem {

    static {
        HanLP.Config.NNParserModelPath  = "D:\\bishe\\moon_back\\moon_db\\data\\model\\dependency\\NNParserModel.txt";
        HanLP.Config.PerceptronCWSModelPath = "D:\\bishe\\moon_back\\moon_db\\data\\model\\perceptron\\large\\cws.bin";
        HanLP.Config.PerceptronPOSModelPath = "D:\\bishe\\moon_back\\moon_db\\data\\model\\perceptron\\pku1998\\pos.bin";
        HanLP.Config.PerceptronNERModelPath = "D:\\bishe\\moon_back\\moon_db\\data\\model\\perceptron\\pku1998\\ner.bin";

    }
    // 决策树节点抽象
    interface DecisionNode {
        FileOperation evaluate(CommandContext context);
    }

    // 条件判断节点
    static class ConditionNode implements DecisionNode {
        private final String conditionKey;
        private final DecisionNode trueBranch;
        private final DecisionNode falseBranch;

        public ConditionNode(String conditionKey, DecisionNode trueBranch, DecisionNode falseBranch) {
            this.conditionKey = conditionKey;
            this.trueBranch = trueBranch;
            this.falseBranch = falseBranch;
        }

        @Override
        public FileOperation evaluate(CommandContext context) {
            return context.hasCondition(conditionKey) ? 
                   trueBranch.evaluate(context) : 
                   falseBranch.evaluate(context);
        }
    }

    // 操作叶子节点
    static class ActionNode implements DecisionNode {
        private final FileOperation operation;

        public ActionNode(FileOperation operation) {
            this.operation = operation;
        }

        @Override
        public FileOperation evaluate(CommandContext context) {
            return operation;
        }
    }

    // 上下文数据结构
    static class CommandContext {
        String operationType;
        Map<String, Object> conditions = new HashMap<>();
        Path sourcePath;
        Path targetPath;

        boolean hasCondition(String key) {
            return conditions.containsKey(key);
        }
    }

    // 文件操作定义
    static class FileOperation {
        String type;
        Path source;
        Path target;
        Map<String, Object> params = new HashMap<>();
    }

    // 构建示例决策树
    private static DecisionNode buildDecisionTree() {
        // 叶子节点
        DecisionNode deleteAction = new ActionNode(new FileOperation() {{
            type = "DELETE";
        }});
        
        DecisionNode moveAction = new ActionNode(new FileOperation() {{
            type = "MOVE";
        }});

        // 条件节点
        return new ConditionNode("timeCondition", 
            new ConditionNode("fileTypeCondition",
                new ConditionNode("keywordCondition", moveAction, deleteAction),
                deleteAction),
            new ConditionNode("fileTypeCondition", 
                deleteAction, 
                new ActionNode(new FileOperation() {{ type = "UNKNOWN"; }}))
        );
    }

    // 主逻辑
    public static void main(String[] args) throws Exception {
        // 1. 输入指令解析
        String command = "删除包含'报告'且超过30天的PDF文件";
        CommandContext context = parseCommand(command);

        // 2. 加载决策树
        DecisionNode decisionTree = buildDecisionTree();

        // 3. 决策执行
        FileOperation operation = decisionTree.evaluate(context);
        executeOperation(operation);
    }

    // 自然语言解析
    private static CommandContext parseCommand(String text) {
        CommandContext context = new CommandContext();
        List<Term> terms = StandardTokenizer.segment(text);
        CoNLLSentence sentence = new NeuralNetworkDependencyParser().parse(terms);

        // 提取操作类型
        context.operationType = extractOperationType(sentence);

        // 提取条件
        context.conditions = extractConditions(sentence);

        // 提取路径（示例简化）获取文件的路径
        context.sourcePath = Paths.get(System.getProperty("user.home"));
        
        return context;
    }

    // 操作类型提取
    private static String extractOperationType(CoNLLSentence sentence) {
        for (CoNLLWord word : sentence.getWordArray()) {
            if (word.POSTAG.startsWith("v")) {
                // 动词
                return word.LEMMA;
            }
        }
        return "UNKNOWN";
    }

    // 条件提取
    private static Map<String, Object> extractConditions(CoNLLSentence sentence) {
        Map<String, Object> conditions = new HashMap<>();
        for (CoNLLWord word : sentence.getWordArray()) {
            if (word.DEPREL.contains("限定")) {
                if (word.LEMMA.matches(".*天$")) {
                    conditions.put("timeCondition", 
                        Long.parseLong(word.LEMMA.replaceAll("[^0-9]", "")));
                } else if (word.LEMMA.endsWith("文件")) {
                    conditions.put("fileTypeCondition", 
                        word.LEMMA.replace("文件", ""));
                } else {
                    conditions.put("keywordCondition", word.LEMMA);
                }
            }
        }
        return conditions;
    }

    // 文件操作执行
    private static void executeOperation(FileOperation op) throws Exception {
        switch (op.type) {
            case "DELETE":
                System.out.println("Deleting files...");
//                Files.walk(op.source)
//                    .filter(p -> matchConditions(p, op.params))
//                    .forEach(p -> {
//                        try { Files.delete(p);
//                        System.out.println("Deleted: " + p);
//                        } catch (IOException e) { /* 错误处理 */ }
//                    });
                break;
                
            case "MOVE":
                System.out.println("Moving files..."    );
//                Files.walk(op.source)
//                    .filter(p -> matchConditions(p, op.params))
//                    .forEach(p -> {
//                        try {
//                            Path target = op.target.resolve(
//                                op.source.relativize(p));
//                            Files.createDirectories(target.getParent());
//                            Files.move(p, target,
//                                StandardCopyOption.REPLACE_EXISTING);
//                            System.out.println("Moved: " + p + " → " + target);
//                        } catch (IOException e) { /* 错误处理 */ }
//                    });
                break;
            default:
                System.out.println("Unsupported operation: " + op.type);
        }
    }

    // 条件匹配
    private static boolean matchConditions(Path file, Map<String, Object> params) {
        try {
            // 时间条件
            if (params.containsKey("timeCondition")) {
                long days = (Long) params.get("timeCondition");
                Instant cutoff = Instant.now().minus(Duration.ofDays(days));
                if (Files.getLastModifiedTime(file).toInstant().isAfter(cutoff)) {
                    return false;
                }
            }
            
            // 文件类型
            if (params.containsKey("fileTypeCondition")) {
                String ext = ((String) params.get("fileTypeCondition")).toLowerCase();
                if (!file.toString().endsWith("." + ext)) return false;
            }
            
            // 关键词
            if (params.containsKey("keywordCondition")) {
                String keyword = (String) params.get("keywordCondition");
                if (!file.getFileName().toString().contains(keyword)) return false;
            }
            
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}